package Service;

import DAO.UserDAO;
import DATA.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "DeleteUser", value = "/DeleteUser")
public class DeleteUser extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        int oldid= (int) session.getAttribute("uid");
        //找名字
        User ans = null;
        try {
            ans = UserDAO.FindbyId(oldid);
        } catch (SQLException e) {
            throw new RuntimeException("数据查询错误");
        }
        if (ans == null) {
            //不存在即登陆已过期
            resp.getWriter().print("登录已过期，3秒后回到登录页面");
            resp.setHeader("refresh", "3;url=/Login.jsp");
//            req.getRequestDispatcher("Login.jsp").forward(req, resp);
        } else {
            //注销个人账号并返回登录页面
            System.out.println("存在");
            try {
                UserDAO.deleteUser(ans.getId());//修改为根据id删除
                session.removeAttribute("user");//登录状态要移除
                session.removeAttribute("uid");//登录状态要移除
                req.getRequestDispatcher("Login.jsp").forward(req,resp);
//                resp.getWriter().print("账户已注销，3秒后回到登录页面");
//                resp.setHeader("refresh", "3;url=/Login.jsp");
            } catch (SQLException e) {
                throw new RuntimeException("注销失败");
            }
        }
    }
}
